package com.antd.common.auth.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.antd.common.auth.security.AntdUserDetails;
import com.antd.common.core.util.R;
import lombok.experimental.UtilityClass;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2020/11/18 16:48
 */
@UtilityClass
public class AntdSecurityUtil {
    private Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public void writeJavaScript(R r, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter printWriter = response.getWriter();
        printWriter.write(JSON.toJSONString(r));
        printWriter.flush();
    }
    public AntdUserDetails getUser(Authentication authentication){
        Object principal = authentication.getPrincipal();
        if (principal instanceof AntdUserDetails) {
            return (AntdUserDetails) principal;
        }
        return null;
    }
    public AntdUserDetails getUser(){
        Authentication authentication=getAuthentication();
        return getUser(authentication);
    }
    public String getUsername(){
        Authentication authentication = getAuthentication();
        if(ObjectUtil.isNull(authentication)){
            return null;
        }
        return authentication.getName();
    }
    public boolean validatePass(String newPass, String passwordEncoderOldPass){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(newPass,passwordEncoderOldPass);
    }

    public String encodePassword(String password){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }
    public static void main(String[] args) {

        System.out.println(encodePassword("123456"));
    }
}
